﻿#include "CameraScreen.h"
#include <QApplication>
#include <QDesktopWidget>
#include <QDebug>
#include "CameraScreen_private.h"

namespace Qly {
CameraScreen::CameraScreen(QObject *parent)
{
    m_pCameraScreen = new CameraScreen_private(this);
    connect(m_pCameraScreen, &CameraScreen_private::imageChanged, this, &CameraScreen::on_imageComming);
}

CameraScreen::~CameraScreen()
{
    m_pCameraScreen->stop();
    delete m_pCameraScreen;
}

bool CameraScreen::isLive()
{
    if(m_pCameraScreen)
    {
        return m_pCameraScreen->isRunning();
    }
    return false;
}

bool Qly::CameraScreen::openCameraByName(QString deviceName)
{
    QList<QScreen *> list = QGuiApplication::screens();
    foreach (QScreen * s, list)
    {
        if( s->name() == deviceName || s->serialNumber() == deviceName )
        {
            return m_pCameraScreen->openDevice(s);
        }
    }
    return false;
}

bool CameraScreen::openDefaultCamera()
{
    return m_pCameraScreen->openDevice(CameraScreenInfo::defaultCamera());
}

bool CameraScreen::startGrabbing()
{
    if(m_pCameraScreen && !m_pCameraScreen->isRunning())
    {
        m_pCameraScreen->start();
        return true;
    }
    return false;
}

bool CameraScreen::stopGrabbing()
{
    if(m_pCameraScreen && m_pCameraScreen->isRunning())
    {
        m_pCameraScreen->stop();
        return true;
    }
    return false;
}

void CameraScreen::close()
{
    stopGrabbing();
}

void CameraScreen::on_imageComming(const QImage &image)
{
    AVPixelFormat format = AV_PIX_FMT_NONE;
    int stride = image.bytesPerLine();

    //qDebug() << "CameraPCVideoSurface::setVideoFrame";
    //qDebug() << frame.pixelFormat();
    switch (image.format())
    {
    case QImage::Format_RGB888:
        format = AV_PIX_FMT_RGB24;
        //emit camera->RGB24ImageChanged(frame.bits(), frame.size());
        break;
    case QImage::Format_RGB32:
    case QImage::Format_ARGB32:
    case QImage::Format_ARGB32_Premultiplied:
        format = AV_PIX_FMT_BGRA;
        //emit camera->RGB32ImageChanged(frame.bits(), frame.size());
        break;
    case QImage::Format_Grayscale8:
        format = AV_PIX_FMT_GRAY8;
        //camera->Bayer8ImageChanged(frame.bits(), frame.size());
        break;
    case QImage::Format_Grayscale16:
        format = AV_PIX_FMT_GRAY16;
        //camera->YUYVImageChanged(frame.bits(), frame.size());
        break;
    case QImage::Format_BGR888:
        format = AV_PIX_FMT_BGR24;
        //camera->UYVYImageChanged(frame.bits(), frame.size());
        break;
    default:
        break;
    }
    VideoFrame videoframe((uint8_t *)image.bits(), stride, image.size(), format);
    videoframe.setExtraInfo(m_imageCount ++, QDateTime::currentDateTime());
    emit videoFrameReady(videoframe);
}

}


